<template>
  <div class="app-container">
    <el-card>
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
      >
        <el-form-item label="设备型号">
          <el-input
            v-model="queryParams.deviceModel"
            placeholder="请输入设备型号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="addDeviceModel"
            >新增</el-button
          >
        </el-col>

        <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>

      <el-table
        v-loading="loading"
        :data="postList"
        stripe
        border
        max-height="500"
      >
        <el-table-column
          label="设备型号"
          align="center"
          prop="deviceModel"
          width="150"
        />
        <el-table-column
          label="设备类型"
          align="center"
          prop="typeName"
          width="150"
        />
        <el-table-column
          label="供应商"
          align="center"
          prop="supplierName"
          width="200"
          show-overflow-tooltip
        />
        <el-table-column label="联网类型" align="center" width="100">
          <template #default="scope">
            <span>
              {{
                network_type.find((item) => item.value == scope.row.networkType)
                  ? network_type.find(
                      (item) => item.value == scope.row.networkType
                    ).label
                  : ""
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="联网方式" align="center" width="200">
          <template #default="scope">
            <el-tag
              v-for="(item, index) in scope.row.deviceNetworkModeList"
              :key="index"
              style="margin-left: 5px"
            >
              {{ item.networkModeName }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="定位功能" align="center" width="80">
          <template #default="scope">
            <span>
              {{
                geolocation.find((item) => item.value == scope.row.geolocation)
                  ? geolocation.find(
                      (item) => item.value == scope.row.geolocation
                    ).label
                  : ""
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="网关设备型号"
          align="center"
          prop="gatewayDeviceTypeName"
        />
        <el-table-column label="采集数据" align="center" width="350">
          <template #default="scope">
            <el-tag
              v-for="(item, index) in scope.row.deviceGatherDataList"
              :key="index"
              style="margin-left: 5px"
            >
              {{ item.gatherDataName }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          label="采购单价（元）"
          align="center"
          prop="purchaseUnitPrice"
        />
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleEdit(scope.row)"
              >修改</el-button
            >
            <el-button
              link
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.page"
        v-model:limit="queryParams.limit"
        @pagination="getList"
      />
    </el-card>
    <el-dialog
      v-model="open"
      :title="title"
      append-to-body
      width="800px"
      v-if="open"
      @close="cancel"
      :close-on-click-modal="false"
    >
      <el-form
        ref="EquipmentRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="设备类型" prop="typeId">
          <el-select
            v-model="form.typeId"
            clearable
            placeholder="请选择设备类型"
            style="width: 100%"
          >
            <el-option
              v-for="dict in deviceList"
              :key="dict.id"
              :label="dict.typeName"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
          <el-select
            v-model="form.supplierId"
            clearable
            placeholder="请选择供应商"
            style="width: 100%"
          >
            <el-option
              v-for="dict in supplier"
              :key="dict.id"
              :label="dict.supplierName"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备型号" prop="deviceModel">
          <el-input v-model="form.deviceModel" placeholder="请输入设备型号" />
        </el-form-item>
        <el-form-item label="联网类型" prop="networkType">
          <el-radio-group v-model="form.networkType">
            <el-radio
              v-for="(item, index) in network_type"
              :key="index"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <div v-if="form.networkType == '2'">
          <el-form-item label="网关设备" prop="gatewayDeviceType">
            <el-select
              v-model="form.gatewayDeviceType"
              clearable
              placeholder="请选择网关设备"
              style="width: 100%"
            >
              <el-option
                v-for="dict in wayList"
                :key="dict.id"
                :label="dict.deviceModel"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item label="联网方式" prop="deviceNetworkModeList">
            <el-checkbox-group v-model="form.deviceNetworkModeList">
              <el-checkbox
                v-for="(item, index) in network_mode"
                :key="index"
                :label="item.value"
                >{{ item.label }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="定位功能" prop="geolocation">
            <el-radio-group v-model="form.geolocation">
              <el-radio
                v-for="(item, index) in geolocation"
                :key="index"
                :label="item.value"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </div>

        <el-form-item label="采集数据" prop="deviceGatherDataList">
          <el-checkbox-group v-model="form.deviceGatherDataList">
            <el-checkbox
              v-for="(item, index) in gather_data"
              :key="index"
              :label="item.value"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="采购单价" prop="purchaseUnitPrice">
          <el-input
            v-model="form.purchaseUnitPrice"
            @input="validateInput"
            placeholder="请输入采购单价"
          >
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="form.notes"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 8 }"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormDebounceHandler"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改岗位对话框 -->
  </div>
</template>

<script setup name="Equipmentmodel">
const { proxy } = getCurrentInstance();
const {
  sys_normal_disable,
  sys_user_sex,
  network_type,
  network_mode,
  geolocation,
  gather_data,
} = proxy.useDict(
  "sys_normal_disable",
  "sys_user_sex",
  "network_type",
  "network_mode",
  "geolocation",
  "gather_data"
);
import {
  devicemodelList,
  devicemodelDel,
  devicetypeList,
  supplierList,
  adddevicemodel,
  updatedevicemodel,
  getGatewayList,
} from "@/api/equipment/index";
import { debounce } from "@/utils/debounce.js";
const showSearch = ref(true);
const loading = ref(true);
const postList = ref([]);
const open = ref(false);
const title = ref("新增设备型号");
const total = ref(0);
const deviceList = ref([]);
const supplier = ref([]);
const wayList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    page: 1,
    limit: 10,
    deviceModel: undefined,
  },
  rules: {
    typeId: [{ required: true, message: "请选择设备类型", trigger: "change" }],
    supplierId: [
      { required: true, message: "请选择供应商", trigger: "change" },
    ],
    deviceModel: [
      { required: true, message: "请输入设备型号", trigger: "blur" },
      { min: 0, max: 10, message: "设备型号过长", trigger: "blur" },
    ],
    deviceNetworkModeList: [
      { required: true, message: "请选择联网方式", trigger: "change" },
    ],
    networkType: [
      { required: true, message: "请选择联网类型", trigger: "change" },
    ],
    geolocation: [
      { required: true, message: "请选择定位功能", trigger: "change" },
    ],
    deviceGatherDataList: [
      { required: true, message: "请选择数据采集", trigger: "change" },
    ],
    purchaseUnitPrice: [
      { required: true, message: "请输入采购单价", trigger: "blur" },
      { min: 0, max: 7, message: "采购单价长度不能超过7", trigger: "blur" },
    ],
    gatewayDeviceType: [
      { required: true, message: "请选择网关设备", trigger: "change" },
    ],
    notes: [
      {
        required: false,
        min: 0,
        max: 500,
        message: "备注不能超过500",
        trigger: "blur",
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询岗位列表 */
function getList() {
  loading.value = true;
  devicemodelList(queryParams.value).then((response) => {
    postList.value = response.page.list;
    total.value = response.page.totalCount;
    loading.value = false;
  });
}
function handleEdit(data) {
  title.value = "编辑设备型号";
  form.value.deviceNetworkModeList = [];
  form.value.deviceGatherDataList = [];
  form.value.id = data.id;
  form.value.notes = data.notes;
  form.value.typeId = data.typeId;
  form.value.supplierId = data.supplierId;
  form.value.deviceModel = data.deviceModel;
  form.value.networkType = data.networkType;
  form.value.geolocation = data.geolocation;
  form.value.gatewayDeviceType = data.gatewayDeviceType - 0;
  form.value.purchaseUnitPrice = data.purchaseUnitPrice.toString();
  for (let i in data.deviceNetworkModeList) {
    form.value.deviceNetworkModeList.push(
      data.deviceNetworkModeList[i].networkModeId
    );
  }
  for (let i in data.deviceGatherDataList) {
    form.value.deviceGatherDataList.push(
      data.deviceGatherDataList[i].gatherDataId
    );
  }

  open.value = true;
}
function transformArrays(arr1, arr2) {
  // 创建一个空数组用于存储结果
  var arr3 = [];
  // 遍历 arr2
  arr2.forEach(function (value) {
    // 在 arr1 中查找与当前值匹配的对象
    var foundItem = arr1.find(function (item) {
      return item.value === value;
    });

    // 如果找到匹配的对象，则将其转换并添加到 arr3 中
    if (foundItem) {
      arr3.push({
        networkModeId: foundItem.value,
        networkModeName: foundItem.label,
      });
    }
  });

  return arr3;
}
function transformArrays1(arr1, arr2) {
  // 创建一个空数组用于存储结果
  var arr3 = [];
  // 遍历 arr2
  arr2.forEach(function (value) {
    // 在 arr1 中查找与当前值匹配的对象
    var foundItem = arr1.find(function (item) {
      return item.value === value;
    });

    // 如果找到匹配的对象，则将其转换并添加到 arr3 中
    if (foundItem) {
      arr3.push({
        gatherDataId: foundItem.value,
        gatherDataName: foundItem.label,
      });
    }
  });

  return arr3;
}
const submitFormDebounceHandler = debounce(submitForm, 500);
function submitForm() {
  proxy.$refs["EquipmentRef"].validate((valid) => {
    if (valid) {
      let arr1 = transformArrays(
        network_mode.value,
        form.value.deviceNetworkModeList
      );
      let arr2 = transformArrays1(
        gather_data.value,
        form.value.deviceGatherDataList
      );

      if (form.value.networkType == "2") {
        form.value.gatewayDeviceType = form.value.gatewayDeviceType;
      } else {
        form.value.gatewayDeviceType = "";
      }
      let obj = {
        id: form.value.id,
        notes: form.value.notes,
        typeId: form.value.typeId,
        supplierId: form.value.supplierId,
        deviceModel: form.value.deviceModel,
        networkType: form.value.networkType,
        gatewayDeviceType: form.value.gatewayDeviceType,
        // deviceNetworkModeList:[],
        // deviceGatherDataList:[],
        geolocation: form.value.geolocation,
        purchaseUnitPrice: form.value.purchaseUnitPrice,
      };
      obj.deviceNetworkModeList = arr1;
      obj.deviceGatherDataList = arr2;
      if (obj.id != undefined) {
        updatedevicemodel(obj).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          reset();
          getList();
        });
      } else {
        adddevicemodel(obj).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          reset();
          getList();
        });
      }
    }
  });
}
function handleQuery() {
  getList();
}
function getdevicetypeList() {
  let obj = {
    page: 1,
    limit: 999,
  };
  devicetypeList(obj).then((res) => {
    deviceList.value = res.page.list;
  });
}
const validateInput = (event) => {
  const regex = /^\d*\.?\d*$/;

  if (!regex.test(event)) {
    // 如果输入不符合规则，则清除非数字和非小数点的字符
    form.value.purchaseUnitPrice = form.value.purchaseUnitPrice.replace(
      /[^\d.]/g,
      ""
    );
  }
};
function getsupplierList() {
  let obj = {
    page: 1,
    limit: 999,
  };
  supplierList(obj).then((res) => {
    supplier.value = res.page.list;
  });
}
function resetQuery() {
  queryParams.value = {
    page: 1,
    limit: 10,
    deviceModel: undefined,
  };
  getList();
}
function handleDelete(row) {
  proxy.$modal
    .confirm("是否确认删除该数据项？")
    .then(function () {
      return devicemodelDel([row.id]);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
function addDeviceModel() {
  title.value = "新增设备型号";
  open.value = true;
}
function getGateway() {
  getGatewayList().then((res) => {
    wayList.value = res.page;
  });
}
function cancel() {
  open.value = false;
  reset();
}
function reset() {
  form.value = {
    id: null,
    notes: undefined,
    typeId: undefined,
    supplierId: undefined,
    deviceModel: undefined,
    networkType: undefined,
    deviceNetworkModeList: [],
    deviceGatherDataList: [],
    geolocation: undefined,
    purchaseUnitPrice: undefined,
    gatewayDeviceType: undefined,
  };
  proxy.resetForm("EquipmentRef");
}
getList();
getdevicetypeList();
getsupplierList();
getGateway();
</script>
